#ifndef THREAD_SAFE_QUEUE_HPP
#define THREAD_SAFE_QUEUE_HPP

#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>

template<typename T>
class ThreadSafeQueue {
public:
    ThreadSafeQueue(size_t max_size = 10) : _max_size(max_size) {}

    // 入队（阻塞直到有空间）
    void Push(const T& item) {
        std::unique_lock<std::mutex> lock(_mutex);
        _cond_not_full.wait(lock, [this]() { return _queue.size() < _max_size; });
        _queue.push(item);
        lock.unlock();
        _cond_not_empty.notify_one();
    }

    // 出队（阻塞直到有数据）
    T Pop() {
        std::unique_lock<std::mutex> lock(_mutex);
        _cond_not_empty.wait(lock, [this]() { return !_queue.empty(); });
        T item = _queue.front();
        _queue.pop();
        lock.unlock();
        _cond_not_full.notify_one();
        return item;
    }

    // 尝试非阻塞出队
    bool TryPop(T& item) {
        std::lock_guard<std::mutex> lock(_mutex);
        if (_queue.empty()) return false;
        item = _queue.front();
        _queue.pop();
        _cond_not_full.notify_one();
        return true;
    }

    void Clear() {
        std::lock_guard<std::mutex> lock(_mutex);
        std::queue<T> empty;
        std::swap(_queue, empty);
    }

private:
    std::queue<T> _queue;
    std::mutex _mutex;
    std::condition_variable _cond_not_empty;
    std::condition_variable _cond_not_full;
    size_t _max_size;
};

#endif // THREAD_SAFE_QUEUE_HPP
